package com.ijustyce.fastandroiddev.crash;

import android.content.Intent;
import android.os.Handler;

import com.ijustyce.fastandroiddev.base.BaseService;
import com.ijustyce.fastandroiddev.unit.LogCat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class CrashReport extends BaseService {

	private Handler handler;
	private String path;
	private File file;
	private String text;

	public void onCreate() {
		super.onCreate();
		
		if(handler == null){
			handler = new Handler();
		}

        initData();
	}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_NOT_STICKY;
    }

	private void initData(){

		String path = app.initFiles() + "/crash/";
		if(file != null && file.exists() && file.isDirectory()){
			int size = file.list().length;
			if(size < 1){
				this.stopSelf();
				return ;
			}
			File f = file.listFiles()[size-1];
			if(f.exists()){
				path = f.getAbsolutePath();
                String fName = f.getName();
                if(!fName.startsWith("crash-") || !fName.endsWith(".log")){
                    f.delete();
                    initData();
                    return;  //  very important
                }
			}
            text = readFile(path ,"utf-8");
            if(text.equals("")){
                this.stopSelf();
                return ;
            }
		}else{
			LogCat.i("===crashReport===", "stop self");
            this.stopSelf();
            return;
        }
        feedback();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(handler != null){
			handler = null;
		}
	}

	private String readFile(String filePath, String encoding) {

		File file = new File(filePath);
		String content = "";
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file), encoding);
			BufferedReader bufferedReader = new BufferedReader(read);
			String line;
			StringBuffer buf = new StringBuffer();
			while ((line = bufferedReader.readLine()) != null) {
				buf.append(line);
			}
			content = buf.toString();
			bufferedReader.close();
			read.close();
		}  catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	
	private void feedback() {

	}
}